//
//  ForgetPasswordViewController.m
//  MangoShangJia
//
//  Created by Macbook on 25/7/17.
//  Copyright © 2017年 dazhou. All rights reserved.
//

#import "ForgetPasswordViewController.h"
#import "RestPasswordViewController.h"
@interface ForgetPasswordViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIButton *ForgetNextBut;
@property (weak, nonatomic) IBOutlet UIButton *CodeBut;
@property (weak, nonatomic) IBOutlet UITextField *MobTextFiled;
@property (weak, nonatomic) IBOutlet UITextField *CodeTextFiled;
@property (weak, nonatomic) IBOutlet UIView *Dview;
@property (weak, nonatomic) NSTimer * timer;
@property (assign, nonatomic) int count;
@end

@implementation ForgetPasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIButton *backbutton = [[UIButton alloc]initWithFrame:CGRectMake(10, 20, 15, 25)];
    [backbutton setBackgroundImage:[UIImage imageNamed:@"香草园地-发布信息_03@2x"] forState:UIControlStateNormal];
    [backbutton addTarget:self action:@selector(goBacktoUp) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithCustomView:backbutton];
    self.navigationItem.leftBarButtonItem = backItem;
    if ([_status isEqualToString:@"1"]) {
        _Dview.frame = CGRectMake(0, 70, UIScreen_WIDTH, 92);
        self.title = @"忘记密码";

    }else{
        _Dview.frame = CGRectMake(0, 0, UIScreen_WIDTH, 92);
        self.title = @"密码重置";

    }
    _MobTextFiled.delegate = self;
    _CodeTextFiled.delegate = self;
    [_MobTextFiled addTarget:self action:@selector(textValueChanged:) forControlEvents:UIControlEventEditingChanged];
    
    [_CodeTextFiled addTarget:self action:@selector(textValueChanged:) forControlEvents:UIControlEventEditingChanged];
    // Do any additional setup after loading the view from its nib.
}
-(void)goBacktoUp{
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)CodeBut:(id)sender
{
    if (![self checkTelphone:_MobTextFiled.text]) {
        return;
    }
    
    NSString * hintStr = [NSString stringWithFormat:@"确定给%@发送短信验证码？", _MobTextFiled.text];
    UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"" message:hintStr delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alertView show];
    
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (1 == buttonIndex) {
        //重新获取验证码
        [self resetGetCodeButtonState];
        [self sendMessageReq];
    }
}
- (void)sendMessageReq
{

    AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
    manger.responseSerializer = [AFJSONResponseSerializer serializer];
    manger.requestSerializer = [AFJSONRequestSerializer serializer];
    manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/ttml", nil];
    NSString *Url = [NSString stringWithFormat:@"%@%@/?type=forgetpassword",ServiceURL,req_SMS];
    NSDictionary *params = @{@"mobile":_MobTextFiled.text};
    
    
    
    [manger POST:Url parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self performSelectorOnMainThread:@selector(delayMe) withObject:nil waitUntilDone:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self performSelectorOnMainThread:@selector(delayMe2) withObject:nil waitUntilDone:YES];
    }];

}
-(void)delayMe{
    [self.view makeToast:@"验证码已发送"];
}
-(void)delayMe2
{
    [self.view makeToast:@"验证码发送失败"];
}
- (BOOL)checkTelphone:(NSString *)telPhone
{
    NSString * regex = @"[0-9]{11,11}";
    NSPredicate * pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL  isRight = [pred evaluateWithObject:_MobTextFiled.text];
    if (!isRight) {
        [self.view makeToast:@"请输入正确的号码"];
    }
    
    return isRight;
}
/** 定时器处理函数 */
- (void)onTimerProcess:(id)sender
{
    self.count --;
    NSString * hintTitle = [NSString stringWithFormat:@"还剩%d(s)", self.count];
    _CodeBut.titleLabel.text = hintTitle;
    
    if (self.count == 0) {
        _CodeBut.enabled = YES;
        [self.timer invalidate];
        self.timer = nil;
        _CodeBut.titleLabel.text = @"获取验证码";
    }
}
- (void)resetGetCodeButtonState
{
    self.count = 60;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(onTimerProcess:) userInfo:nil repeats:YES];
    _CodeBut.enabled = NO;
    _CodeBut.titleLabel.text = @"60(s)";
    _CodeBut.titleLabel.textColor = UIColorFromRGBA(0xf2a002, 1);
    
}

-(IBAction)ForgetNextBut:(id)sender{
    
    AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
    manger.responseSerializer = [AFJSONResponseSerializer serializer];
    manger.requestSerializer = [AFJSONRequestSerializer serializer];
    manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/ttml", nil];
    NSString *token = [USERDEFAULT objectForKey:@"token"];

    NSString *Url = [NSString stringWithFormat:@"%@%@",ServiceURL,req_checkCodeb];
    NSLog(@"url=====%@",Url);
    NSDictionary *params = @{@"mobile":_MobTextFiled.text,@"code":_CodeTextFiled.text,@"token":token};
    
    
    
    [manger POST:Url parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
          NSString *code = responseObject[@"code"];
        if ([code isEqualToString:@"0"]) {
            [self performSelectorOnMainThread:@selector(check1) withObject:nil waitUntilDone:YES];
 
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self performSelectorOnMainThread:@selector(check2) withObject:nil waitUntilDone:YES];
    }];

}
-(void)check1{
        RestPasswordViewController* restPassVC = [[RestPasswordViewController alloc]init
        ];
        restPassVC.MobStr = _MobTextFiled.text;
        restPassVC.CodeStr = _CodeTextFiled.text;
        restPassVC.titleStr = @"密码重置";
        [self.navigationController pushViewController:restPassVC animated:YES];

}
-(void)check2{
    [self.view makeToast:@"验证码错误"];
}
- (void)textValueChanged:(UITextField *)sender {
    
    if (_MobTextFiled.text.length>=11&&_CodeTextFiled.text.length>=4) {
        
        _ForgetNextBut.backgroundColor = UIColorFromRGBA(0x3cb83a, 1);
        
        _ForgetNextBut.userInteractionEnabled = YES;
        
    } else if (_MobTextFiled.text.length<11||_CodeTextFiled.text.length<4) {
        
        
        _ForgetNextBut.backgroundColor = UIColorFromRGBA(0xdfdfdf, 1);
        
        _ForgetNextBut.userInteractionEnabled = NO;
        
    }
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
